package MQ.WorkQueues;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
 * @Title: MQ.WorkQueues.NewTask.java 
 * @Package MQ.WorkQueues 
 * @Description: TODO(MQ往队列中放消息) 
 * @Copyright: Copyright (c) 2017 YUANH All Rights Reserved
 * @author yuanh
 * @date 2017-5-10 下午3:50:35
 */
public class NewTask {
	private final static String QUEUE_NAME = "hello";

	public static void main(String[] args) throws IOException, TimeoutException {
		// 创建连接连接到MabbitMQ
		ConnectionFactory factory = new ConnectionFactory();
		// 设置MabbitMQ所在主机ip或者主机名
		factory.setHost("127.0.0.1");
		factory.setUsername("yuanh");
		factory.setPassword("yuanh");
		factory.setPort(5672);
		factory.setVirtualHost("y_yuanh");
		Connection connection = factory.newConnection();
		// 创建一个频道
		Channel channel = connection.createChannel();
		// 创建一个队列
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		String message = getMessage(args);
		// 将消息放到队列里面
		channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
		System.out.println(" 发送 '" + message + "'");
		// 关闭通道和连接
		channel.close();
		connection.close();
	}
	
	private static String getMessage(String[] strings){
	    if (strings.length < 1)
	        return "Hello World..!";
	    return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
	    int length = strings.length;
	    if (length == 0) return "";
	    StringBuilder words = new StringBuilder(strings[0]);
	    for (int i = 1; i < length; i++) {
	        words.append(delimiter).append(strings[i]);
	    }
	    return words.toString();
	}

}
